package com.furnitur.common.aspect;

import com.furnitur.common.annotation.MerchantOperation;
import com.furnitur.common.service.DataPermissionService;
import com.furnitur.core.entity.user.User;
import com.furnitur.core.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class MerchantOperationAspect {

    @Autowired
    private UserService userService;
    
    @Autowired
    private DataPermissionService dataPermissionService;

    @Around("@annotation(merchantOperation)")
    public Object checkMerchantOperation(ProceedingJoinPoint joinPoint, MerchantOperation merchantOperation) throws Throwable {
        User currentUser = userService.getCurrentUser();
        log.info("Checking merchant operation for user: {}", currentUser);
        
        // 检查用户是否是商家
        if (currentUser.getRoleId() != 2L) {
            log.warn("Non-merchant user attempting operation: {}", currentUser);
            throw new RuntimeException("非商家用户无权操作");
        }
        
        // 如果需要检查所属权
        if (merchantOperation.checkOwnership()) {
            // 获取方法参数
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            String[] parameterNames = signature.getParameterNames();
            Object[] args = joinPoint.getArgs();
            
            // 查找ID参数（通常是第一个Long类型参数）
            Long resourceId = null;
            for (int i = 0; i < args.length; i++) {
                if (args[i] instanceof Long) {
                    resourceId = (Long) args[i];
                    break;
                }
            }
            
            // 验证资源所属权
            if (resourceId != null && !dataPermissionService.verifyResourceOwnership(
                    merchantOperation.resourceType(), resourceId)) {
                log.warn("Merchant {} attempting to access unauthorized resource: {}", 
                        currentUser.getId(), resourceId);
                throw new RuntimeException("无权访问该资源");
            }
        }
        
        return joinPoint.proceed();
    }
} 